using System;
using System.Collections;
using System.Collections.Generic;
using Rokid.UXR.Module;
using UnityEngine;

public class MultiTrackImage : MonoBehaviour
{
    // 图片名与预制体的映射
    [SerializeField]
    private List<PrefabMapping> prefabMappings;

    // 用于动态管理的字典
    private Dictionary<int, GameObject> prefabDictionary = new Dictionary<int, GameObject>();
    private Dictionary<int, GameObject> spawnedPrefabs = new Dictionary<int, GameObject>();

    [System.Serializable]
    public class PrefabMapping
    {
        public int imageId;
        public GameObject prefab;
    }

    private void Awake()
    {
        // 构建图片名与预制体的字典
        foreach (var mapping in prefabMappings)
        {
            if (!prefabDictionary.ContainsKey(mapping.imageId))
            {
                prefabDictionary[mapping.imageId] = mapping.prefab;
            }
        }
    }

    private void OnEnable()
    {
        // 订阅图像变化事件
        ARTrackedImageManager.OnTrackedImageAdded += OnTrackedImageAdded;
        ARTrackedImageManager.OnTrackedImageUpdated += OnTrackedImageUpdated;
        ARTrackedImageManager.OnTrackedImageRemoved += OnTrackedImageRemoved;
    }

    private void OnTrackedImageRemoved(ARTrackedImage trackedImage)
    {
        int index = trackedImage.index;

        // 如果已实例化虚拟对象，则销毁它
        if (spawnedPrefabs.ContainsKey(index))
        {
            Destroy(spawnedPrefabs[index]);
            spawnedPrefabs.Remove(index);
        }
    }

    private void OnTrackedImageUpdated(ARTrackedImage image)
    {
        OnTrackedImageAdded(image);
    }

    private void OnTrackedImageAdded(ARTrackedImage trackedImage)
    {
        int index = trackedImage.index;

        // 如果字典中有对应的预制体
        if (prefabDictionary.ContainsKey(index))
        {
            // 如果已存在对应的预制体，则更新位置和旋转
            if (spawnedPrefabs.ContainsKey(index))
            {
                spawnedPrefabs[index].transform.position = trackedImage.pose.position;
                spawnedPrefabs[index].transform.rotation = trackedImage.pose.rotation;
            }
            else
            {
                // 如果不存在，则实例化新的预制体
                GameObject newPrefab = Instantiate(prefabDictionary[index], trackedImage.pose.position, trackedImage.pose.rotation);
                spawnedPrefabs[index] = newPrefab;
            }

            // 激活预制体（如果图像已被识别）
            spawnedPrefabs[index].SetActive(true);
        }
    }

    private void OnDisable()
    {
        // 取消订阅图像变化事件
        ARTrackedImageManager.OnTrackedImageAdded -= OnTrackedImageAdded;
        ARTrackedImageManager.OnTrackedImageUpdated -= OnTrackedImageUpdated;
        ARTrackedImageManager.OnTrackedImageRemoved -= OnTrackedImageRemoved;
    }

    
}
